package io.github.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import io.github.annotation.Log;
import io.github.entity.AnswerGroupEntity;
import io.github.entity.ExtensionEntity;
import io.github.pojo.ExtensionPojo;
import io.github.service.AnswerGroupService;
import io.github.service.ExtensionService;
import io.github.service.excel.listener.ExtensionListener;
import io.github.util.CommandUtils;
import io.github.util.PageUtils;
import io.github.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Max
 * <br>
 * date 2019/12/27 15:25
 * <br>
 *
 * 分机列表
 */

@RestController
@RequestMapping("/api/v1/extension")
public class ExtensionController extends AbstractController{

    @Autowired
    ExtensionService extensionService;

    @Autowired
    AnswerGroupService answerGroupService;

    /**
     * 分机列表查询
     * @param jsonObject json
     * @return info
     */
    @RequestMapping("/list")
    @Log(value="分机列表查询",action = 0)
    public R list(@RequestBody JSONObject jsonObject) {
        Integer offset = jsonObject.getInteger("offset");
        Integer limit = jsonObject.getInteger("limit");
        //分机号
        String number = jsonObject.getString("number");

        Boolean status = jsonObject.getBoolean("status");

        Integer gid = jsonObject.getInteger("gid");

        Page pageList =  extensionService.queryListPage(offset,limit,number,status,gid);
        List<ExtensionEntity> resultList = pageList.getRecords();

        System.out.println("状态查询");
        //List<String> statusList = new CommandUtils().exeStatus();
        Map<String,String> statusMap = new CommandUtils().exeStatus();
        System.out.println("size:"+statusMap.size());

        for(ExtensionEntity entity:resultList) {

            Iterator it = statusMap.entrySet().iterator();
            while(it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                if(entry.getKey().equals(entity.getNumber())){
                    entity.setStatus(true);
                    entity.setIp((String) entry.getValue());
                }
            }
//            if(statusList.contains(entity.getNumber())) {
//                entity.setStatus(true);
//            }else {
//                entity.setStatus(false);
//            }
        }

        PageUtils pageUtils = new PageUtils(resultList,pageList.getTotal(),pageList.getSize(),pageList.getCurrent());
        return R.ok().put("data",pageUtils);
    }


    /**
     * 单个分机添加
     * @return info
     */
    @RequestMapping("/add")
    @Log(value="分机添加",action = 1)
    public R save(@RequestBody ExtensionEntity entity) {
        try {
            extensionService.save(entity);
            return R.ok();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error(500,"分机添加失败");
        } catch(IllegalArgumentException e){
            return R.error(400,"已经存在该分机");
        }
    }

    /**
     * 单个分机更新
     * @param entity entity
     * @return info
     */
    @RequestMapping("/update")
    @Log(value="分机信息更新")
    public R update(@RequestBody ExtensionEntity entity) {
        try {
            extensionService.updateExtension(entity);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error(500,"分机更新失败");
        }
        return R.ok();
    }

    /**
     * 闹钟批量修改
     * @param json
     * @return
     */
    @RequestMapping("/updateBatch")
    public R updateBatch(@RequestBody JSONObject json) {
        extensionService.updateClock(json);
        return R.ok();
    }

    /**
     * 批量导入分机数据
     * @param file 导入数据文件
     * @return info
     */
    @RequestMapping("/importExcel")
    public R excelImport(@RequestParam("file")MultipartFile file){

        try {
            EasyExcel.read(file.getInputStream(), ExtensionPojo.class,new ExtensionListener(extensionService,answerGroupService)).sheet().doRead();
            CommandUtils.reload();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 得到导入模板
     * @param response response
     * @throws IOException
     */
    @RequestMapping("/getModel")
    public void getModel(HttpServletResponse response) throws IOException {
        List list = new ArrayList<>();
        response.setHeader("Content-disposition","attachment;filename=model.xlsx");
        EasyExcel.write(response.getOutputStream(),ExtensionPojo.class).sheet("分机列表").doWrite(list);
    }

    /**
     * 分机批量删除
     * @param json ids
     */
    @RequestMapping("/delete")
    @Log(value = "分机删除",action = 3)
    public R delete(@RequestBody JSONObject json) {
        JSONArray ids = json.getJSONArray("ids");
        extensionService.deleteBatch(toArrays(ids));
        return R.ok();
    }

    /**
     * 应答组 添加
     * @param entity json
     * @return info
     */
    @RequestMapping("/groupSave")
    public R groupSave(@RequestBody AnswerGroupEntity entity) {
        answerGroupService.save(entity);
        return R.ok();
    }

    @RequestMapping("/groupList")
    public R groupList() {
        return R.ok().put("data",answerGroupService.list());
    }

    @RequestMapping("/groupDelete")
    public R groupDelete(@RequestBody JSONObject json) {
        Long id = json.getLong("id");

        try {
            answerGroupService.delete(id);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return R.error(400,"这个代答组中还有分机");
        }
        return R.ok();
    }

    @RequestMapping("/simSeqEdit")
    public R edit(@RequestBody JSONObject json) {
        extensionService.simSeqEdit(json);
        return R.ok();
    }

}